package com.example.springbootdemo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.handler.inter.IWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootdemo.bean.entity.User;
import com.example.springbootdemo.service.IUserService;
import com.example.springbootdemo.service.impl.ExcelExportStylerCustomizeImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author hh
 * @date 2022/3/11
 */
@RequestMapping("test")
@RestController
public class ExcelController {

    private final IUserService userService;

    public ExcelController(IUserService userService) {
        this.userService = userService;
    }

    /**
     * Excel文件导入
     * @param file 文件
     * @return String
     */
    @PostMapping("import")
    public String importExcel(MultipartFile file){
        try {
            ImportParams importParams = new ImportParams();
            // 表格标题所占的行数
            importParams.setTitleRows(0);
            // 表格表头所占的行数
            importParams.setHeadRows(1);
            List<User> list = ExcelImportUtil.importExcel(file.getInputStream(), User.class, importParams);
            list.forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
            return "失败";
        }
        return "成功";
    }

    /**
     * 大数据量导出
     * @param response response
     */
    @GetMapping("exportBigData")
    public void exportBigData(HttpServletResponse response) {
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("sheet1");
        exportParams.setTitle("用户数据");
        exportParams.setStyle(ExcelExportStylerCustomizeImpl.class);
        // 每行的行高
        exportParams.setHeight((short) 10);

        Workbook workbook = null;
        int size = 3;
        try {
            IWriter<Workbook> workbookWriter = ExcelExportUtil.exportBigExcel(exportParams, User.class);
            long totalCount = userService.count();
            long pages = totalCount / size + 1;

            for (int i = 0; i < pages; i++) {
                Page<User> page = new Page<>(i + 1, size);
                IPage<User> userPage = userService.getUserPage(page);
                List<User> records = userPage.getRecords();
                workbookWriter.write(records);
            }

            workbook = workbookWriter.get();

            String fileName = URLEncoder.encode("大批量用户数据", "UTF-8").replaceAll("\\+", "%20");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * Excel一般导出
     * @param response response
     */
    @GetMapping("export")
    public void export(HttpServletResponse response) {
        List<User> users = userService.getUserByUserName(null);
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("sheet1");
        exportParams.setTitle("用户数据");
        exportParams.setStyle(ExcelExportStylerCustomizeImpl.class);
        // 每行的行高
        exportParams.setHeight((short) 10);

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, users);
        try {
            String fileName = URLEncoder.encode("用户数据", "UTF-8").replaceAll("\\+", "%20");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
